package cn.com.sinosoft.ares.channel.service;

import cn.com.sinosoft.ares.common.util.JSONObjectTools;
import cn.com.sinosoft.ares.common.util.XMLTools;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.StringWriter;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Description: 美团模板抽象类
 * Author: lishangmin
 * Created: 2018-09-13 14:12
 */
@Slf4j
public abstract class AbstractMTTemplateService extends AbstractTemplateService {

    /**
     * 解析美团报文格式
     * @param query 请求URL-query
     */
    protected Map<String ,String> parse(String query){
        String[] params = query.split("&");
        Map<String, String> map = new HashMap<>();
        try {
            for (String param : params) {
                if(param.startsWith("xml=")){
                    String name = "xml";
                    String value = param.replaceFirst("xml=", "");
                    map.put(name, StringUtils.trim(URLDecoder.decode(value,"UTF-8")));
                }else{
                    String[] strs = param.split("=");
                    String name = strs[0];
                    String value = strs[1];
                    map.put(name,StringUtils.trim(URLDecoder.decode(value,"UTF-8")));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public String fromXML(String message,String template) {
        Map<String ,String> map = this.parse(message);
        String sign = map.get("sign");
        this.validSignature(map.get("xml"),sign,"");
        VelocityContext context = new VelocityContext();
        map.forEach((k,v) ->{
            if(k.equals("xml")){
                JSONObjectTools xmlJSONObj = XMLTools.toJSONObject(v);
                String jsonStr = xmlJSONObj.toString();
                log.info("jsonStr:{}",jsonStr);
                context.put(k, XMLTools.toJSONObject(v));
            }else {
                context.put(k, v);
            }
        });
        StringWriter stringWriter = new StringWriter();
        Velocity.evaluate(context, stringWriter, "xmlVM", template);
        return stringWriter.toString();
    }
}
